package stack;

/**
 * @author yunfei.shang
 * @date 2017/6/7.
 * @descreption 优先队列
 */
public class PriorityQueue {
    private static int[] queueArray;
    private static int index = 0;

    public static void main(String[] args) {
        queueArray = new int[5];
        insertQueue(20);
        insertQueue(3);
        insertQueue(25);
        insertQueue(18);
        insertQueue(21);
        for (int item : queueArray) {
            System.out.println(item);
        }
        removeQuery(5);
        insertQueueBack(20);
        insertQueueBack(3);
        insertQueueBack(25);
        insertQueueBack(18);
        insertQueueBack(21);
        for (int item : queueArray) {
            System.out.println(item);
        }
    }

    /**
     * 正向思维的优先队列
     *
     * @param item
     */
    public static void insertQueue(int item) {
        if (index == 0) {
            queueArray[index] = item;
        } else if (queueArray.length != index) {
            for (int i = 0; i < index; i++) {
                if (queueArray[i] > item) {
                    int temp = queueArray[i];
                    for (int j = i; j < index + 1; j++) {
                        int temp1 = 0;
                        if (j == i) {
                            queueArray[j] = item;
                        } else {
                            temp1 = queueArray[j];
                            queueArray[j] = temp;
                            temp = temp1;
                        }
                    }
                    break;
                } else if (i == index - 1) {
                    queueArray[index] = item;
                }
            }
        }
        index++;
    }

    /**
     * 反向排序
     *
     * @param item
     */
    public static void insertQueueBack(int item) {
        if (index == 0) {
            queueArray[index] = item;
        } else if (index < queueArray.length) {
            for (int j = index; j >= 0; j--) {
                if (j > 0 && queueArray[j - 1] > item) {
                    queueArray[j] = queueArray[j - 1];
                } else {
                    queueArray[j] = item;
                    break;
                }
            }
        }
        index++;
    }

    public static void removeQuery(int length) {
        queueArray = new int[length];
        index = 0;
    }
}
